import { Button, message, Drawer, Divider, Avatar, Space } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import moment from 'moment';
import {
  selectUsingPOST,
  updateStatusByIdsUsingPOST,
  updateUsingPOST,
} from '@/services/test/Employ';
import { ModalForm, ProFormDateTimePicker } from '@ant-design/pro-form';
import WarningAlert from '@/components/warning-alert';
import { UserOutlined } from '@ant-design/icons';

// 批量通过
const handlePass = async (selectedRows: any[]) => {
  const hide = message.loading('正在通过');
  if (!selectedRows) return true;
  try {
    await updateStatusByIdsUsingPOST({
      employIds: selectedRows.map((row) => row.id),
      status: 2,
    });
    hide();
    message.success('通过成功');
    return true;
  } catch (error) {
    hide();
    message.error('通过失败，请重试');
    return false;
  }
};

// 批量删除
const handleRemove = async (selectedRows: any[]) => {
  const hide = message.loading('正在淘汰');
  if (!selectedRows) return true;
  try {
    await updateStatusByIdsUsingPOST({
      employIds: selectedRows.map((row) => row.id),
      status: 3,
    });
    hide();
    message.success('淘汰成功');
    return true;
  } catch (error) {
    hide();
    message.error('淘汰失败，请重试');
    return false;
  }
};

// 单条记录通过
const onPass = async (values: any) => {
  const hide = message.loading('正在通过');
  //  初审
  if (values.status === 0) {
    try {
      await updateUsingPOST({ id: values.id, status: 2 });
      hide();
      message.success('通过成功');
      return true;
    } catch (error) {
      hide();
      message.error('通过失败，请重试');
      return false;
    }
  }
  // 面试通过
  if (values.status === 4) {
    try {
      await updateUsingPOST({ id: values.id, status: 7 });
      hide();
      message.success('通过成功');
      return true;
    } catch (error) {
      hide();
      message.error('通过失败，请重试');
      return false;
    }
  }
};

// 单条记录淘汰
const onOut = async (values: any) => {
  const hide = message.loading('正在淘汰');
  // 初审淘汰
  if (values.status === 0 || values.status === 2) {
    try {
      await updateUsingPOST({ id: values.id, status: 3 });
      hide();
      message.success('淘汰成功');
      return true;
    } catch (error) {
      hide();
      message.error('淘汰失败，请重试');
      return false;
    }
  }
  // 面试后淘汰
  if (values.status === 4) {
    try {
      await updateUsingPOST({ id: values.id, status: 6 });
      hide();
      message.success('淘汰成功');
      return true;
    } catch (error) {
      hide();
      message.error('淘汰失败，请重试');
      return false;
    }
  }
};

const getUrlLast = (url: string) => {
  const index = url.lastIndexOf('/');
  return url.substring(index + 1, url.length);
};

const Index: React.FC = (props: any) => {
  const postId: string = props.location.query.postId;
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);

  const columns: ProColumns<any>[] = [
    {
      title: '姓名',
      key: 'name',
      render: (dom: any, entity) => {
        return (
          <>
            <Avatar
              size={24}
              style={{ margin: '5px' }}
              src={dom.userId.photo}
              icon={<UserOutlined />}
            />
            <a
              onClick={() => {
                setCurrentRow(entity);
                setShowDetail(true);
              }}
            >
              {dom.userId.name}
            </a>
          </>
        );
      },
    },
    {
      title: '投递岗位',
      key: 'postId',
      render: (dom: any) => {
        return <p>{dom.postId.name}</p>;
      },
    },
    {
      title: '所学专业',
      key: 'userId',
      hideInSearch: true,
      render: (dom: any) => {
        return <p>{dom.userId.major}</p>;
      },
    },
    {
      title: '最高学历',
      hideInSearch: true,
      render: (dom: any) => {
        return <p>{dom.userId.education}</p>;
      },
    },
    {
      title: '最高学位',
      hideInSearch: true,
      render: (dom: any) => {
        return <p>{dom.userId.degree}</p>;
      },
    },
    {
      title: '毕业学校',
      hideInSearch: true,
      render: (dom: any) => {
        return <p>{dom.userId.school}</p>;
      },
    },
    // 审核状态：0已投递，1审核中，2审核通过，3淘汰，4面试中，5面试通过，6面试淘汰，7资格审查中，8资格审查淘汰，9入职
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '已投递',
          status: 'Default',
        },
        1: {
          text: '审核中',
          status: 'Processing',
        },
        2: {
          text: '初审通过',
          status: 'Success',
        },
        3: {
          text: '淘汰',
          status: 'Error',
        },
        4: {
          text: '面试中',
          status: 'Processing',
        },
        5: {
          text: '面试通过',
          status: 'Success',
        },
        6: {
          text: '面试淘汰',
          status: 'Error',
        },
        7: {
          text: '资格审查中',
          status: 'Processing',
        },
        8: {
          text: '资格审查淘汰',
          status: 'Error',
        },
        9: {
          text: '入职',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        [0, 1, 4].includes(record.status) && (
          <a
            key="out"
            onClick={async () => {
              await onPass(record);
              actionRef.current?.reload?.();
            }}
            style={{ marginRight: '12px' }}
          >
            通过
          </a>
        ),
        [0, 1, 2, 4].includes(record.status) && (
          <a
            key="out"
            onClick={async () => {
              await onOut(record);
              actionRef.current?.reload?.();
            }}
            style={{ marginRight: '12px' }}
          >
            淘汰
          </a>
        ),
        [2].includes(record.status) && (
          <a
            key="interview"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow(record);
              actionRef.current?.reload?.();
            }}
            style={{ marginRight: '12px' }}
          >
            邀请面试
          </a>
        ),
      ],
    },
  ];

  const desColumn: ProColumns<any>[] = [
    {
      title: '姓名',
      dataIndex: ['userId', 'name'],
    },
    {
      title: '照片',
      dataIndex: ['userId', 'photo'],
      render: (text) => {
        return <Avatar shape="circle" size={128} src={text} />;
      },
    },
    {
      title: '电话',
      dataIndex: ['userId', 'phone'],
      copyable: true,
    },
    {
      title: '邮箱',
      dataIndex: ['userId', 'email'],
      copyable: true,
    },
    {
      title: '性别',
      dataIndex: ['userId', 'sex'],
    },
    {
      title: '身份证号码',
      dataIndex: ['userId', 'identityNum'],
    },
    {
      title: '所学专业',
      dataIndex: ['userId', 'major'],
    },
    {
      title: '最高学历',
      dataIndex: ['userId', 'education'],
    },
    {
      title: '最高学位',
      dataIndex: ['userId', 'degree'],
    },
    {
      title: '毕业学校',
      dataIndex: ['userId', 'school'],
    },
    {
      title: '政治面貌',
      dataIndex: ['userId', 'politicsStatus'],
    },
    {
      title: '民族',
      dataIndex: ['userId', 'nation'],
    },
    {
      title: '婚姻状况',
      dataIndex: ['userId', 'maritalStatus'],
    },
    // 审核状态：0已投递，1审核中，2审核通过，3淘汰，4面试中，5面试通过，6面试淘汰，7资格审查中，8资格审查淘汰，9入职
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '已投递',
          status: 'Default',
        },
        1: {
          text: '审核中',
          status: 'Processing',
        },
        2: {
          text: '审核通过',
          status: 'Success',
        },
        3: {
          text: '淘汰',
          status: 'Error',
        },
        4: {
          text: '面试中',
          status: 'Processing',
        },
        5: {
          text: '面试通过',
          status: 'Success',
        },
        6: {
          text: '面试淘汰',
          status: 'Error',
        },
        7: {
          text: '资格审查中',
          status: 'Processing',
        },
        8: {
          text: '资格审查淘汰',
          status: 'Error',
        },
        9: {
          text: '入职',
          status: 'Success',
        },
      },
    },
    {
      title: '简历附件',
      dataIndex: ['userId', 'attachment'],
      span: '2',
      render: (text: any) => {
        // return <a href={text} target = "_blank" rel="noreferrer">{getUrlLast(text)}</a>;
        return <a>{text}</a>;
      },
    },
  ];

  const getList = async (params?: any) => {
    const res = await selectUsingPOST({ ...params, postId: postId });
    return res;
  };

  return (
    <PageContainer content={'点击候选人名称可以查看投递记录，仅限初审的候选人可批量处理'}>
      <ProTable<any, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          pageSize: 10,
        }}
        // 获取列表
        request={getList}
        // 列表名称
        columns={columns}
        // 选择当前行
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {/* 批量处理 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项 &nbsp;&nbsp;
            </div>
          }
        >
          {/* 批量删除 */}
          <Button
            onClick={async () => {
              await handlePass(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量淘汰
          </Button>

          {/* 批量审批 */}
          <Button
            type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量审批
          </Button>
        </FooterToolbar>
      )}

      {/* 点名称查看详情 */}
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.userId && (
          <>
            <ProDescriptions
              column={2}
              title={'投递信息'}
              request={async () => ({
                data: currentRow || {},
              })}
              columns={desColumn}
            >
              <ProDescriptions.Item span={2}>
                <Divider />
              </ProDescriptions.Item>
              <ProDescriptions.Item label={'投递岗位'}>
                {currentRow?.postId.name} &nbsp;&nbsp;
              </ProDescriptions.Item>
              <ProDescriptions.Item label={'投递时间'}>
                {moment(currentRow?.utcCreate).format('YYYY-MM-DD HH:mm')}
              </ProDescriptions.Item>

              {currentRow?.firstPeople ? (
                <>
                  <ProDescriptions.Item label={'初审审核人'}>
                    {currentRow?.firstPeople.name}
                  </ProDescriptions.Item>
                  <ProDescriptions.Item label="初审审核时间" valueType="dateTime">
                    {moment(currentRow?.firstTime).format('YYYY-MM-DD HH:mm')}
                  </ProDescriptions.Item>
                </>
              ) : undefined}

              {currentRow?.secondPeople ? (
                <>
                  <ProDescriptions.Item label={'二轮面试安排人'}>
                    {currentRow?.secondPeople.name}
                  </ProDescriptions.Item>
                  <ProDescriptions.Item label="面试时间" valueType="dateTime">
                    {moment(currentRow?.secondTime).format('YYYY-MM-DD HH:mm')}
                  </ProDescriptions.Item>
                </>
              ) : undefined}

              {currentRow?.thirdPeople ? (
                <>
                  <ProDescriptions.Item label={'二轮面试官'}>
                    {currentRow?.thirdPeople.name}
                  </ProDescriptions.Item>

                  <ProDescriptions.Item label={'面试通过时间'}>
                    {moment(currentRow?.thirdTime).format('YYYY-MM-DD HH:mm')}
                  </ProDescriptions.Item>
                  {/* <ProDescriptions.Item label={'第三次面试评价'} span={2}>
                    {currentRow?.thirdEvaluate}
                  </ProDescriptions.Item> */}
                </>
              ) : undefined}

              {currentRow?.remark ? (
                <>
                  <ProDescriptions.Item label={'资格审查附件'} span={2}>
                    <a href={currentRow.remark} target="_blank" rel="noreferrer">
                      {getUrlLast(currentRow?.remark)}
                    </a>
                  </ProDescriptions.Item>
                </>
              ) : undefined}

              {currentRow?.forthPeople ? (
                <>
                  <ProDescriptions.Item label={'资格审查官'}>
                    {currentRow?.forthPeople.name}
                  </ProDescriptions.Item>
                  <ProDescriptions.Item label="资格审核时间" valueType="dateTime">
                    {moment(currentRow?.forthTime).format('YYYY-MM-DD HH:mm')}
                  </ProDescriptions.Item>
                </>
              ) : undefined}
            </ProDescriptions>
          </>
        )}
      </Drawer>
      <ModalForm
        title={'选择面试时间'}
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await updateUsingPOST({
            id: currentRow.id,
            status: 4,
            secondTime: value.secondTime,
          });
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        initialValues={currentRow || {}}
      >
        <WarningAlert text="点击确认后系统会自动发送邮件给该用户" />
        <ProFormDateTimePicker
          name="secondTime"
          label="日期时间"
          rules={[
            {
              required: true,
              message: '请选择面试时间',
            },
          ]}
          transform={(value) => {
            return {
              secondTime: moment(value).format('YYYY-MM-DDTHH:mm:00'),
            };
          }}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default Index;
